import os
import random
import re
import time
import traceback
import threading

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait

import setting
# from YeMao import setting

from publicapi.publicdef import *

test_url = 'https://yun.yemaogj.com'
dev_test_rul = 'http://yun.ym.dev.6fenkj.com'
url = dev_test_rul

dr = webdriver.Chrome(setting.WEBDRIVERURI)
dr.implicitly_wait(10)
dr.maximize_window()


def select_rand(xpath):
    """
    随机选择一个下拉项
    :param xpath: 下拉框的xpath
    :return:
    """
    selecter = Select(
        dr.find_element_by_xpath(xpath))
    selecter.select_by_index(random.randint(1, len(selecter.options)))


def getelmt(by: By, xpath):
    """
    等待加载对象完成
    :param by: xpath方式 By.xpath....
    :param xpath: 对象xpath
    :return: 返回完成后的对象
    """

    return WebDriverWait(dr, 10).until(EC.presence_of_element_located((by, xpath)), "默认提示，你不管")


def getelmts(by: By, xpath):
    """
    等待加载对象完成
    :param by: xpath方式 By.xpath....
    :param xpath: 对象xpath
    :return: 返回完成后的对象
    """
    return WebDriverWait(dr, 10).until(EC.presence_of_all_elements_located((by, xpath)), "默认提示，你不管")


def getmaxpages(by: By, xpath):
    """
    获取最大页码数
    :return:
    """

    indextext = getelmt(by, xpath).text  # 获取数据总条数
    maxpages = int(re.findall('\d+', indextext)[0]) // 50 + 1
    return maxpages


def login():
    """
    登录
    :return:
    """
    try:
        dr.get(url + '/login')
        username = getelmt(By.ID, 'login_account')
        # username = dr.find_element_by_id('login_account')
        username.clear()  # 清除原有数据
        username.send_keys(setting.USERNAME)  # 输入帐号
        pwd = getelmt(By.ID, 'login_pwd')  # dr.find_element_by_id('login_pwd')
        pwd.clear()
        pwd.send_keys(setting.PASSWORD)
        getelmt(By.CSS_SELECTOR, '[class="lg_btn bd-radius-max"]').send_keys(Keys.ENTER)
        time.sleep(setting.WaitTime)
        if dr.title == "夜猫管理平台-数据概括":
            logtofile('登录成功', logger.info)
            return True
        else:
            logtofile('登录失败', logger.info)
            return False
    except Exception as e:
        logtofile('登录出错%s' % e, logger.error)
    finally:
        time.sleep(1.5)
        dr.get(url + '/Home')


def GoodsPurchase():
    """
    采购商品
    :return:
    """
    try:
        getelmt(By.XPATH, '//*[@id="app"]/div/div[1]/ul/li[3]/div/a/span').click()  # 点击一级菜单 商品管理
        # dr.find_element_by_xpath('//*[@id="app"]/div/div[1]/ul/li[3]/div/a/span').click()
        # time.sleep(setting.WaitTime)
        getelmt(By.XPATH, '//*[@id="app"]/div/div[1]/ul/li[3]/div/ul/li[1]/a').click()  # 点击商品管理
        getelmt(By.XPATH, '//*[@id="app"]/div/div[2]/div[2]/div/div[1]/div/a[4]').click()  # 点击商品采购
        # getelmt(By.XPATH, '//*[@id="app"]/div/div[2]/div[2]/div/div[2]/div/div[1]/div[1]/select').click()  # 点击供应商下拉框
        # getelmt(By.XPATH, '//*[@id="app"]/div/div[2]/div[2]/div/div[2]/div/div[1]/div[1]/select/option[{}]'.format(
        #     random.randint(3, 11))).click()
        select_rand('//*[@id="app"]/div/div[2]/div[2]/div/div[2]/div/div[1]/div[1]/select')  # 随机选择一个下拉属性

        getelmt(By.XPATH, '//*[@id="app"]/div/div[2]/div[2]/div/div[3]/div/input[1]').click()
        # getelmt(By.XPATH, '//*[@class="ym_pages"]/ul/div/div/div/div/div/span').click()
        # getelmt(By.XPATH, '//*[@class="ym_pages"]/ul/div/div/div/div/ul/li[1]').click()  # 设置每页数量 商品
        getelmt(By.XPATH, '//*[@class="ym_pages"]//input[@spellcheck="false"]').clear()  # 点击页码输入框
        maxpages = getmaxpages(By.XPATH, '//*[@class="ivu-page-total"]')
        getelmt(By.XPATH, '//*[@class="ym_pages"]//input[@spellcheck="false"]').send_keys(
            '{}'.format(random.randint(1, maxpages)))  # 随机选择一页商品

        getelmt(By.XPATH, '//*[@class="ym_pages"]//input[@spellcheck="false"]').send_keys(Keys.ENTER)  # 随机选择一页商品

        getelmt(By.XPATH, '//*/table/thead//tr[1]//input').click()  # 选择页面内全部商品

        getelmt(By.XPATH, '//*[@value="批量添加"]').click()

        # 返回输入框列表

        tr_list = getelmts(By.XPATH, '//*[@id="ym_table"]//div[2]//tr')

        # 输入采购数据
        for index, tr in enumerate(tr_list):
            # if index < 3:
            #     print("当前第%s个tr" % index)
            #     continue
            td_list = tr.find_elements_by_xpath('.//input')
            td_list[1].send_keys('10')
            td_list[3].send_keys('10')
        btndict = {
            1: '入库',
            2: '入库并上库'
        }
        # getelmt(By.XPATH, '//*[@id="app"]/div/div[2]/div[2]/div/div[3]/div/input[2]').click()  # 点击入库
        getelmt(By.XPATH, '//*[@value="{}"]'.format(btndict[random.randint(1, 2)])).click()

        logtofile('采购商品', logger.info)

    except Exception as e:
        logtofile('采购出错%s' % e, logger.error)
        traceback.print_exc()
    finally:
        time.sleep(1.5)
        dr.get(url + '/Home')


def GoodsRelease(n):
    """
    上下架操作
    :param n: 根据传入的值决定是上架还是下架
    :return:
    """
    try:

        getelmt(By.XPATH, '//*[@id="app"]/div/div[1]/ul/li[3]/div/a/span').click()  # 点击商品管理
        getelmt(By.XPATH, '//*[@id="app"]/div/div[1]/ul/li[3]/div/ul/li[1]/a').click()  # 点击商品管理
        getelmt(By.XPATH, '//*[@id="app"]/div/div[2]/div[2]/div/div[1]/div/a[5]').click()  # 点击商品上下架

        getelmt(By.XPATH, '//*[@value="添加商品"]').click()

        getelmt(By.XPATH, '//*[@class="ym_pages"]//input[@spellcheck="false"]').clear()
        maxpages = getmaxpages(By.XPATH, '//*[@class="ivu-page-total"]')
        getelmt(By.XPATH, '//*[@class="ym_pages"]//input[@spellcheck="false"]').send_keys(
            '{}'.format(random.randint(1, maxpages)))  # 随机选择一页商品

        getelmt(By.XPATH, '//*[@class="ym_pages"]//input[@spellcheck="false"]').send_keys(Keys.ENTER)  # 随机选择一页商品

        getelmt(By.XPATH, '//*/table/thead//tr[1]//input').click()  # 选择页面内全部商品

        getelmt(By.XPATH, '//*[@value="批量添加"]').click()

        # 返回输入框列表
        tr_list = getelmts(By.XPATH, '//*[@id="ym_table"]//div[2]//tr')
        numb = random.randint(1, 50)
        # 输入采购数据
        for index, tr in enumerate(tr_list):
            # if index < 3:
            #     print("当前第%s个tr" % index)
            #     continue
            tr.find_element_by_xpath('.//input').send_keys("{numb}".format(numb=numb))  # 随机输入上下架数量
        if n % 2 == 0:
            getelmt(By.XPATH, '//*[@value="上架"]').click()  # 上架
        else:
            getelmt(By.XPATH, '//*[@value="下架"]').click()  # 下架
        logtofile('上下架成功', logger.info)

    except Exception as e:
        logtofile('上下架出错%s' % e, logger.error)
        traceback.print_exc()
    finally:
        time.sleep(1.5)
        dr.get(url + '/Home')


def GoodsReturn():
    """
    退货
    :return:
    """
    try:
        getelmt(By.XPATH, '//*[@id="app"]/div/div[1]/ul/li[3]/div/a/span').click()  # 点击商品管理
        getelmt(By.XPATH, '//*[@id="app"]/div/div[1]/ul/li[3]/div/ul/li[1]/a').click()  # 点击商品管理
        getelmt(By.XPATH, '//*[@id="app"]/div/div[2]/div[2]/div/div[1]/div/a[6]').click()  # 点击商品上下架
        select_rand('//*[@id="app"]/div/div[2]/div[2]/div/div[2]/div/div[1]/div[1]/select')  # 点击供应商下拉框
        getelmt(By.XPATH, '//*[@value="添加商品"]').click()  # 进入商品选择页面
        getelmt(By.XPATH, '//*[@class="lbox-head ym_table_head"]/div[4]/div/label[2]').click()  # 有库存

        getelmt(By.XPATH, '//*[@class="ym_pages"]//input[@spellcheck="false"]').clear()
        maxpages = getmaxpages(By.XPATH, '//*[@class="ivu-page-total"]')
        getelmt(By.XPATH, '//*[@class="ym_pages"]//input[@spellcheck="false"]').send_keys(
            '{}'.format(random.randint(1, maxpages)))  # 随机选择一页商品

        getelmt(By.XPATH, '//*[@class="ym_pages"]//input[@spellcheck="false"]').send_keys(Keys.ENTER)  # 随机选择一页商品

        getelmt(By.XPATH, '//*/table/thead//tr[1]//input').click()  # 选择页面内全部商品

        getelmt(By.XPATH, '//*[@value="批量添加"]').click()

        # 返回输入框列表
        tr_list = getelmts(By.XPATH, '//*[@id="ym_table"]//div[2]//tr')

        numb = random.randint(1, 50)
        # 输入退货数据
        for index, tr in enumerate(tr_list):
            # if index < 3:
            #     print("当前第%s个tr" % index)
            #     continue
            td_list = tr.find_elements_by_xpath('.//input')
            td_list[1].send_keys(numb)
            td_list[3].send_keys(numb)

        getelmt(By.XPATH, '//*[@value="保存退货单"]').click()  # 点击保存退货单

        logtofile('退货成功', logger.info)
        # dr.refresh()
    except Exception as e:
        logtofile('退货出错%s' % e, logger.error)
        traceback.print_exc()
    finally:
        time.sleep(1.5)
        dr.get(url + '/Home')


def GoodsAdd():
    """
    添加新的商品
    :return:
    """

    try:

        getelmt(By.XPATH, '//*[@id="app"]/div/div[1]/ul/li[3]/div/a/span').click()  # 点击商品管理
        getelmt(By.XPATH, '//*[@id="app"]/div/div[1]/ul/li[3]/div/ul/li[1]/a').click()  # 点击商品管理

        getelmt(By.XPATH, '//*[@href="/GoodsAdd"]').click()  # 点击编辑商品资料

        getelmt(By.XPATH, '//*[@id="app"]/div/div[2]/div[2]/div/div[2]/div/div[1]/div/a[2]').click()  # 点击添加商品

        getelmt(By.XPATH, '//*[@value="选择系统图片"]').click()  # 点击选择图片

        inputxpath = '/html/body/div[3]/div/div/div[1]/div[2]/div/div[3]/div/ul/div/div/input'
        getelmt(By.XPATH, inputxpath).clear()  # ' //*[@class="ym_pages"]//input[@spellcheck="false"]'
        maxpages = getmaxpages(By.XPATH, '//*[@class="ivu-page-total"]')
        getelmt(By.XPATH, inputxpath).send_keys(
            '{}'.format(random.randint(1, maxpages)))  # 随机选择一页商品

        getelmt(By.XPATH, inputxpath).send_keys(Keys.ENTER)  # 随机选择一页
        index = random.randint(1, 11)
        time.sleep(1)
        getelmt(By.XPATH, '//*[@class="vl-notify-content"]//ul/li[{index}]'.format(index=index)).click()  # 随机选择一张图片，点击

        getelmt(By.XPATH, '//*[@class="vl-notify-content"]//*[@value="确定添加"]').click()  # 点击确定添加 返回数据输入页面
        # 随机生成商品名称
        goodname = ""
        for i in range(1, random.randint(1, 6)):
            goodname += GBK2312()
        getelmt(By.XPATH, '//*[@class="ym_formgroup"]//input[1]').clear()
        getelmt(By.XPATH, '//*[@class="ym_formgroup"]//input[1]').send_keys(goodname)
        # 设置商品分类
        select_rand('//*[@id="app"]/div/div[2]/div[2]/div/div[2]/div/div[2]/div[1]/div[3]/div/select')

        # 设置单位
        select_rand('//*[@id="app"]/div/div[2]/div[2]/div/div[2]/div/div[2]/div[1]/div[4]/div/select')

        getelmt(By.XPATH, '//*[@placeholder="零售价"]').send_keys(random.randint(1, 50))

        getelmt(By.XPATH, '//*[@placeholder="成本价"]').send_keys(random.randint(1, 50))

        getelmt(By.XPATH, '//*[@id="app"]/div/div[2]/div[2]/div/div[2]/div/div[2]/div[4]/input[2]').click()

        logtofile('添加商品成功', logger.info)

        # dr.refresh()  # 刷新下页面
    except Exception as e:
        logtofile('添加商品出错%s' % e, logger.error)
        traceback.print_exc()
    finally:
        time.sleep(2)
        dr.get(url + '/Home')


def StockGoodsList(n):
    """
    商品盘点
    :return:
    """
    try:
        print("进来了")

        getelmt(By.XPATH,'//*[@id="app"]/div/div[1]/ul/li[3]/div/a/span').click()  # 点击商品管理
        getelmt(By.XPATH,'//*[@href="/StockGoodsList"]').click()  # 点击商品库存


        pandian = WebDriverWait(dr, 10).until(EC.element_to_be_clickable(
            (By.XPATH, '//*[@id="app"]/div/div[2]/div[2]/div/div[2]/div/div[1]/div[1]/div/label[2]')), '激流雕文工行')
        pandian.click()
        # dr.find_element_by_xpath(
        #     '//*[@id="app"]/div/div[2]/div[2]/div/div[2]/div/div[1]/div[1]/div/label[2]').click()  # 点击盘点

        getelmt(By.XPATH,'//*[@value="选择商品"]').click()


        maxpages = getmaxpages(By.XPATH, '//*[@class="ivu-page-total"]')
        inputxpath = '/html/body/div[3]/div/div/div[3]/ul/div/div[2]/input'  # 页码输入框
        inputelm = getelmt(By.XPATH, inputxpath)  # ' //*[@class="ym_pages"]//input[@spellcheck="false"]'
        inputelm.clear()
        inputelm.send_keys(
            '{}'.format(n))  # 随机选择一页商品,,,  .format(random.randint(1, maxpages)
        inputelm.send_keys(Keys.ENTER)  # 随机选择一页
        time.sleep(1)

        getelmt(By.XPATH, '//*/table/thead//tr[1]//input').click()  # 选择页面内全部商品   //*/table/thead//tr[1]//input
        # WebDriverWait(dr, 10).until(EC.presence_of_element_located((By.XPATH, '//*/table/thead//tr[1]//input')), "默认提示，你不管").click()

        getelmt(By.XPATH, '//*[@value="批量添加"]').click()

        tr_list = getelmts(By.XPATH, '//*[@id="ym_table"]//div[2]//tr')  # 获取到输入框列表
        # numb = random.randint(50, 500)  # random.randint(50, 500) 500
        numb = 4000
        # 输入盘点数据
        for index, tr in enumerate(tr_list):
            # if index < 3:
            #     print("当前第%s个tr" % index)
            #     continue
            td_list = tr.find_elements_by_xpath('.//input')
            td_list[0].send_keys(numb)
            td_list[1].send_keys(numb)
        # time.sleep(setting.WaitTime)
        getelmt(By.XPATH, '//*[@value="保存"]').click()  # 保存盘点
        logtofile('盘点成功', logger.info)
    except Exception as e:
        logtofile('盘点出错%s' % e, logger.error)
        traceback.print_exc()
    finally:
        time.sleep(3)
        dr.get(url + '/Home')


def DelGoods():
    try:
        getelmt(By.XPATH, '//*[@id="app"]/div/div[1]/ul/li[3]/div/a/span').click()  # 点击一级菜单  商品管理
        getelmt(By.XPATH, '//*[@href="/GoodsList"]').click()  # 点击商品管理
        delbtn = getelmt(By.XPATH, '//*[@id="ym_table"]/div/div[1]/div[2]/table/tbody/tr[1]/td[11]/div/div/p[2]/a[3]')
        if delbtn:
            delbtn.click()
            getelmt(By.XPATH, '/html/body/div[3]/div[2]/div/div/div/div/div[3]/button[2]/span').click()
            logtofile('删除商品成功', logger.info)
        else:
            dr.refresh()

    except Exception as e:
        logtofile('删除商品出错%s' % e, logger.error)
        traceback.print_exc()
    finally:
        time.sleep(1.5)
        dr.get(url + '/Home')


# 主方法入口
def run():
    try:
        resbool = login()  # 打开登录页
        isok = 0
        if resbool:
            starttime = time.ctime()
            for i in range(1, 100):
                try:

                    # GoodsAdd()  # 添加新商品
                    # GoodsPurchase()  # 采购
                    # GoodsRelease(i)  # 上下架
                    # GoodsReturn()  # 退货
                    StockGoodsList(i)  # 盘点
                    # DelGoods()
                    isok += 1
                except Exception as e:
                    traceback.print_exc()
                finally:
                    print('当前总成功次数为:{}'.format(isok))
                    endtime = time.ctime()
                    print("开始时间:\n", starttime)
                    print("结束时间:\n", endtime)


        else:
            logintime = time.strftime('%Y-%m-%d:%H-%M-%S', time.localtime(time.time()))
            logger.warning("{} 登录失败".format(logintime))
            dr.close()
    except Exception as e:
        dr.quit()  # 任何错误都结束浏览器驱动程序
        print("出错了", e)
        traceback.print_exc()

    finally:
        dr.quit()  # 执行完程序后结束浏览器驱动


if __name__ == '__main__':
    while True:
        run()
